package com.motorola.dp.jenkinsmonitor.webapp.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.motorola.dp.jenkinsmonitor.service.util.properties.ClasspathPropertiesService;

@Configuration
@EnableTransactionManagement
@ImportResource("classpath:springDataConfig.xml")
public class PersistenceConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
       LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
       factoryBean.setDataSource(restDataSource());
       factoryBean.setPackagesToScan(new String[ ] {"com.motorola.dp.jenkinsmonitor.model.*"});

       JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

       factoryBean.setJpaVendorAdapter(vendorAdapter);
       factoryBean.setJpaProperties(datalayerProperties());

       return factoryBean;
    }

    @Bean
    public DataSource restDataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();
       dataSource.setConnectionProperties(datalayerProperties());

       dataSource.setDriverClassName(property("driverClassName"));
       dataSource.setUrl(property("url"));
       dataSource.setUsername(property("username"));
       dataSource.setPassword(property("password"));
       return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
       JpaTransactionManager transactionManager = new JpaTransactionManager();
       transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());

       return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
       return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public Properties datalayerProperties() {
        return ClasspathPropertiesService.readPropsFromClasspath("datalayer.properties");
    }

    private String property(String propertyName) {
        return datalayerProperties().getProperty(propertyName);
    }
}
